package org.seefly.iprint.controller;

import lombok.Setter;
import org.seefly.iprint.entity.User;
import org.seefly.iprint.service.UserService;
import org.seefly.iprint.utils.CheckCodeUtil;
import org.seefly.iprint.vo.RegisterUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@ConfigurationProperties(prefix = "user.register")
@Setter
public class RegisterController {

    @Autowired
    private UserService service;
    /**注册成功*/
    private String success;
    /**注册失败*/
    private String fail;
    /**用户名不可用*/
    private String accountDisabled;
    /**用户名可用*/
    private String accountUesble;


    /**
     * 
     * 获取注册页面
     * @return 页面地址
     */
    @RequestMapping("/register")
    public String register(Model m) {
        m.addAttribute("type", "register");
        return "front/login";
    }
    
    /**
     * 用户注册
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public String doRegister(@RequestBody RegisterUserVo vo, HttpSession session) {
        String msg = null;
        //校验验证码
        String registerCode = (String) session.getAttribute("registerCode");
        //判断验证码
        if(registerCode != null && registerCode.equalsIgnoreCase(vo.getCode())) {
            User user = service.doRegister(vo);
            session.setAttribute("user", user);
            msg = success;
        }else {
            msg = fail;
        }
        return msg;
    }
    
    /**
     * 
     * 返回注册验证码图片，值放入session中
     * @param session 存放验证码值
     * @param response 异步响应图片io流
     */
    @RequestMapping("/registerCode")
    public void returnRegisterCodeImg(HttpSession session,HttpServletResponse response) throws IOException {
      //创建一张内存图片
        int width = 30 * 4;
        int height = 30;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        String msg = CheckCodeUtil.getCode(bufferedImage);
        //写入session
        session.setAttribute("registerCode", msg);
        // 图片输出 ImageIO
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }
    
    
    /**
     * 异步校验注册用户名是否被占用
     */
    @RequestMapping("/verifyName")
    @ResponseBody
    public String verifyName(String name) {
        boolean isExist = service.verifyName(name);
        return isExist?accountDisabled:accountUesble;
    }
}
